package com.maple.excel.controller;

import com.maple.excel.entity.Customer;
import com.maple.excel.entity.CustomerExportDTO;
import com.maple.excel.service.IExcelService;
import com.maple.excel.utils.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>控制类</p>
 *
 * @author maple
 */
@Controller
@Slf4j
public class ExcelController {

    @Resource
    private IExcelService excelService;

    @RequestMapping("/demo")
    @ResponseBody
    public String demo() {
        return "ok";
    }

    @PostMapping("/customer/import")
    @ResponseBody
    public Boolean createFromFile(@RequestParam("file") MultipartFile multipart) {
        File file = new File(UUID.randomUUID().toString());
        try {
            FileUtils.copyInputStreamToFile(multipart.getInputStream(), file);

            return excelService.createFromFile(file);
        } catch (Exception e) {
            log.error("导入客户信息失败！", e);
        } finally {
            if (file.exists()) {
                try {
                    Files.delete(file.toPath());
                } catch (IOException ie) {
                    log.error(ie.getMessage(), ie);
                }
            }
        }
        return true;
    }

    @GetMapping("/customer/export")
    public void exportCustomer(HttpServletResponse response) {
        try {
            List<Customer> customers = new ArrayList<>();
            Customer customer = new Customer();
            customer.setName("李三");
            customer.setGender(1);
            customer.setCreateTime(LocalDateTime.now());
            customers.add(customer);

            customer = new Customer();
            customer.setName("王五");
            customer.setGender(2);
            customers.add(customer);

            if (CollectionUtils.isEmpty(customers)) {
                log.info("没有搜索到客户可以导出");
            }
            EasyExcelUtils.export(response, CustomerExportDTO.class, customers.stream()
                    .map(CustomerExportDTO::format).collect(Collectors.toList()), "客户列表", "customers");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.info("导出异常：" + e.getMessage());
        }
    }

}
